package com.sky.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.vo.BackstageTagVO;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 贾晓晨
 * @version 1.0
 */
public class StringToListTypeHandler  extends BaseTypeHandler<List<BackstageTagVO.TagLinkVO>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<BackstageTagVO.TagLinkVO> parameter, JdbcType jdbcType) throws SQLException {
        // 写入逻辑（根据需求实现）
    }

    @Override
    public List<BackstageTagVO.TagLinkVO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJsonArray(rs.getString(columnName));
    }

    @Override
    public List<BackstageTagVO.TagLinkVO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJsonArray(rs.getString(columnIndex));
    }

    @Override
    public List<BackstageTagVO.TagLinkVO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJsonArray(cs.getString(columnIndex));
    }

    private List<BackstageTagVO.TagLinkVO> parseJsonArray(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return Collections.emptyList();
            }
            return objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class,
                            BackstageTagVO.TagLinkVO.class
                    ));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 解析失败: " + json, e);
        }
    }
}